﻿using FlowCanvas.Nodes;
using UnityEngine;
using Yoozoo.Gameplay.City;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    public class SwitchCityCameraEffect : CallableActionNode<bool>
    {
        public static bool IS_ADD;
        public static ResLoader _resLoader;
        public static GameObject _effect;
        
        public override void Invoke(bool isAdd)
        {
            IS_ADD = isAdd;
            if (isAdd)
            {
                if (_effect == null)
                {
                    if (_resLoader == null)
                    {
                        _resLoader = ResLoader.Alloc();
                    }

                    _resLoader.Add2Load("Assets/ResourcesAssets/City/Effect/sfx_ui_shuye.prefab", ((success, assetName, asset) =>
                    {
                        if (!IS_ADD)
                        {
                            if (_resLoader!=null)
                            {
                                _resLoader.Recycle2Cache();
                                _resLoader = null;
                            }
                            return;
                        }
                        
                        if (!success)
                        {
                            return;
                        }
                        
                        _effect = GameObject.Instantiate(asset as GameObject);
                        // 给到UICanvas
                        
                        var root = GameObject.Find("RootCanvas");
                        if (root)
                        {
                            _effect.transform.SetParent(root.transform);
                            ((RectTransform)_effect.transform).anchoredPosition = new Vector2(-953,353);
                        }
                        // var cityCamera = CityManager.Instance.mobileTouchCamera.GetComponent<Camera>();
                        // _effect.transform.SetParent(cityCamera.transform);
                        // _effect.transform.localPosition = Vector3.zero;
                        // _effect.transform.localRotation = Quaternion.identity;
                    }));
                    _resLoader.Load();
                }
            }
            else
            {
                if (_effect)
                {
                    GameObject.Destroy(_effect);
                    _effect = null;
                }

                if (_resLoader!=null)
                {
                    _resLoader.Recycle2Cache();
                    _resLoader = null;
                }
            }
        }
    }
}